<?php

namespace common\models;

use Yii;
use common\helpers\ArrayHelper;
use common\models\user\UserConnect;

/**
 * 第三方登录授权
 * ThirdPartyAuthForm
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class ThirdPartyAuthorization extends \common\base\Model {

    /**
     * @var string 外接第三方登录标识
     */
    public $client;

    /**
     * @var string 第三方接口返回的授权code
     */
    public $code;

    /**
     * @var 用户模型
     */
    public $token = null;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['client', 'code'], 'required'],
            [['client'], 'in', 'range' => UserConnect::getConstants('client'), 'message' => '{attribute}不在允许的授权范围内'],
        ];
    }

    /**
     * bind
     * @return BaseUser|null the saved model or null if saving fails
     */
    public function getAuthData() {
        return null;
    }

    /**
     * bind
     * @return BaseUser|null the saved model or null if saving fails
     */
    public function authent() {
        if (!$this->validate()) {
            $this->dumpError('授权参数校验失败');
        }
        $client = $this->client;
        $code = $this->code;
        $openid = null;
        $unionid = null;
        $data = [];
        if ($client == UserConnect::CLIENT_WECHAT) {
            $wechat = Yii::$app->openWechat;
            $data = $wechat->getOauth2AccessToken($code);
            $openid = ArrayHelper::getValue($data, 'openid');
            $unionid = ArrayHelper::getValue($data, 'unionid');
        } elseif ($client == UserConnect::CLIENT_WEIBO) {
            /* @var $weibo \xj\oauth\WeiboAuth */
            $weibo = Yii::$app->authClient->getClient('weibo');
            $token = [
                'token' => $code,
                'tokenParamKey' => 'client_id',
                'tokenSecretParamKey' => 'client_secret',
            ];
            $weibo->setAccessToken($token);
            $data = $weibo->getUserAttributes();

            Yii::error($data, __METHOD__);

            $openid = ArrayHelper::getValue($data, 'uid');
            $unionid = '';
        }
        if (!$openid) {
            return false;
        }
        $condition = compact('client', 'openid', 'unionid');
        $connect = UserConnect::findOrNew($condition);
        if (!$connect->save()) {
            return false;
        }
        $connect->setCacheToken($data);
        return $connect;
    }

}
